package com.stud.seckill.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.stud.seckill.common.enums.CacheKeyEnum;
import com.stud.seckill.common.config.CacheService;
import com.stud.seckill.mapper.SeckillOrderMapper;
import com.stud.seckill.entity.OrderEntity;
import com.stud.seckill.entity.SeckillOrderEntity;
import com.stud.seckill.service.OrderService;
import com.stud.seckill.service.SeckillGoodsService;
import com.stud.seckill.service.SeckillOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 秒杀订单表 服务实现类
 * </p>
 *
 * @author Libra
 * @since 2024-03-30
 */
@Service
public class SeckillOrderServiceImpl extends ServiceImpl<SeckillOrderMapper, SeckillOrderEntity> implements SeckillOrderService {

    @Autowired
    private SeckillGoodsService seckillGoodsService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private CacheService cacheService;

    @Override
    public Long getResult(Long userId, Long goodsId) {

        LambdaQueryWrapper<SeckillOrderEntity> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(SeckillOrderEntity::getUserId, userId);
        queryWrapper.eq(SeckillOrderEntity::getGoodsId, goodsId);
        SeckillOrderEntity seckillOrder = this.getBaseMapper().selectOne(queryWrapper);
        if (seckillOrder != null) {
            return seckillOrder.getOrderId();
        } else if (cacheService.hasKey(CacheKeyEnum.秒杀监控数据, "orderSuc:userId"+userId+"goodsId"+goodsId)) {
            return 0L;
        }
        return -1L;
    }

    @Transactional
    @Override
    public OrderEntity saveOrder(Long userId, Long goodsId) {

        // 扣减库存
        seckillGoodsService.subStore(goodsId, 1);

        // 先生成普通订单
        OrderEntity order = orderService.saveOrder(userId, goodsId);

        // 生成秒杀订单
        SeckillOrderEntity seckillOrder = new SeckillOrderEntity();
        seckillOrder.setUserId(userId);
        seckillOrder.setOrderId(order.getId());
        seckillOrder.setGoodsId(goodsId);
        this.getBaseMapper().insert(seckillOrder);

        // cacheService.set(CacheKeyEnum.秒杀监控数据, "orderSuc:userId"+userId+"goodsId"+goodsId, 1);

        return order;
    }

    @Override
    public void initOrder() {
        this.remove(Wrappers.lambdaQuery());
    }

}
